Lists and strings

Lists are data arrays. They can contain elements of different types (integers, floats).

An example of a list is


In [ ]:
l = [1,4.5, 6, 9.0, 10, -1]

In [ ]:
l

The most basic operation on a list is extracting its elements at a given position. For that we use the position in the list keeping in mind that the first element starts at 0.


In [ ]:
l[0]

In [ ]:
l[5]

The indexing also works backwards using negative numbers


In [ ]:
l[-1]

In [ ]:
l[-3]

If you try to use an index beyond the list size you will get an error


In [ ]:
l[6]

Lists are mutable. That means you can change the value of an item as follows


In [ ]:
l[0] = 100

In [ ]:
l

Slicing

Arguably, the most useful list operation is slicing. You can use it to quickly select a subset from the list. Slicing consists in using two different indices separated by : to select the elements with the syntax l[start:end]

Here are some examples. Please be sure that you understand how tthe start:end indexing works!. That's the whole point of slicing, if some of the examples are unclear, please ask!


In [ ]:
print(l) # this is the full list

In [ ]:
l[0:4] #start=0, end=4

In [ ]:
l[2:4] #start=2, end=4

In [ ]:
l[-4:-1] #start=-4, end=-1, negative values are allowed.

Slicing also works if you use only one index.


In [ ]:
l[3:]

In [ ]:
l[:4]

The mathematical operations + and * can also be used with lists. The first operation is used for concatenation and the second for repetition.


In [ ]:
m = [45, -56]
print('l=', l)
print('m=', m)
n = l + m
print('n=',n) # this is the concatenation

In [ ]:
m + l #sum of lists does not commute!

In [ ]:
2 * l # here I am reapeating the list `l` two times.

The function sorted can be used on lists to reorder the objects


In [ ]:
l_sorted = sorted(l)
print(l_sorted)

and the function len gives you the number of items in the list


In [ ]:
len(l)

In python the strings are defined as a list of characters


In [ ]:
given_name = "Silvia"
family_name = "Rivera Cusicanqui"

In [ ]:
print(given_name + " " + family_name) # This is the concatenations of the strings

These strings have many useful methods


In [ ]:
given_name.upper() #convert to upper case

In [ ]:
given_name.replace('i', 'y') #replace 'i' with 'y'

In [ ]:
given_name.count('i') # count how many times 'i' is the string

In [ ]:
family_name.split() # split the original string in the places with spaces, the result is a new list.

Exercise 2.01

  • Define a list with the integers from 1 to 10 and use slicing print the second half of the list.

In [ ]:

Exercise 2.02

  • Build a list with 100 repetitions of the sequence 1, -1 (i.e. [1,-1,1,-1,1,-1,...])

In [ ]:

Exercise 2.03

  • Build a list that contains a 1 surrounded by 15 zeroes on the left and the right.

In [ ]:

Exercise 2.04

  • Compute the median of the following list

a = [21, 48, 79, 60, 77, 15, 43, 90, 5, 49, 15, 52, 20, 70, 55, 4, 86, 49, 87, 59]


In [ ]: